import SwiftUI

struct ProfileHost: View {
    // SwiftUI provides storage in the environment for values you can access using the @Environment property wrapper. 
    // Here use it to access the editMode value that’s built into the environment to read or write the edit scope.
    @Environment(\.editMode) var editMode
    @Environment(ModelData.self) var modelData
    @State private var draftProfile = Profile.default
    
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            HStack {
                // Unlike the Done button that EditButton provides, the Cancel button doesn’t apply the edits to the real profile data in its closure.
                if editMode?.wrappedValue == .active {
                    Button("Cancel", role: .cancel) {
                        draftProfile = modelData.profile
                        editMode?.animation().wrappedValue = .inactive
                    }
                }
                
                Spacer()
                // The EditButton controls the same editMode environment value
                EditButton()
            }

            if editMode?.wrappedValue == .inactive {
                // To avoid updating the global app state before confirming any edits
                // such as while the user enters their name
                // the editing view operates on a copy of itself.
                ProfileSummary(profile: modelData.profile)
            } else {
                ProfileEditor(profile: $draftProfile)
                    .onAppear {
                        draftProfile = modelData.profile
                    }
                    .onDisappear {
                        modelData.profile = draftProfile
                    }
            }
        }
        .padding()
    }
}

#Preview {
    ProfileHost()
        // Even though this view doesn’t use a property with the @Environment property wrapper, ProfileSummary, a child of this view, does. So without the modifier, the preview fails.
        .environment(ModelData())
}
